from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockMasterFlowPhase(Base):
    __tablename__ = 'stock_master_flow_phase'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    t = Column(String(10))
    jlr3 = Column(String(20))
    jlr5 = Column(String(20))
    jlr10 = Column(String(20))
    jlrl3 = Column(String(10))
    jlrl5 = Column(String(10))
    jlrl10 = Column(String(10))

    def __init__(self, code, t, jlr3, jlr5, jlr10, jlrl3, jlrl5, jlrl10):
        self.code = code
        self.t = t
        self.jlr3 = jlr3
        self.jlr5 = jlr5
        self.jlr10 = jlr10
        self.jlrl3 = jlrl3
        self.jlrl5 = jlrl5
        self.jlrl10 = jlrl10

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_stock_master_flow_phase = session.query(StockMasterFlowPhase).filter_by(code=code,
                                                                                             t=data['t']).first()
            if existing_stock_master_flow_phase:
                existing_stock_master_flow_phase.jlr3 = data['jlr3']
                existing_stock_master_flow_phase.jlr5 = data['jlr5']
                existing_stock_master_flow_phase.jlr10 = data['jlr10']
                existing_stock_master_flow_phase.jlrl3 = data['jlrl3']
                existing_stock_master_flow_phase.jlrl5 = data['jlrl5']
                existing_stock_master_flow_phase.jlrl10 = data['jlrl10']
            else:
                session.add(StockMasterFlowPhase(code=code, t=data['t'], jlr3=data['jlr3'], jlr5=data['jlr5'],
                                                 jlr10=data['jlr10'], jlrl3=data['jlrl3'], jlrl5=data['jlrl5'],
                                                 jlrl10=data['jlrl10']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
